<template>
    <div class="ct-bodySet">
        <el-container>
            <el-header class="bgclr-dk-sp0 mb20 headerCoster" >
                <el-row>
                    <el-col :span="20">
                        <el-breadcrumb separator-class="el-icon-arrow-right">
                            <el-breadcrumb-item :to="{ path: '/mainPage/welcome' }">首页</el-breadcrumb-item>
                            <el-breadcrumb-item>角色权限管理</el-breadcrumb-item>
                            <el-breadcrumb-item :to="{ path: '/mainPage/userRefRoleManage' }">角色用户关联</el-breadcrumb-item>
                            <el-breadcrumb-item><span class="main-Clr-ft">添加用户</span></el-breadcrumb-item>
                        </el-breadcrumb>
                    </el-col>
                    <el-col :span="4" class="textAlignRight buttonLineHeight">
                        <el-button type="text" @click="back" icon="el-icon-back" size="small" class="main-Clr-ft">返回</el-button>
                    </el-col>
                </el-row>
            </el-header>

            <div class="pl20 pr20">
                <el-card class="mb20 cardWidth">
                    <div slot="header">
                    <span>
                        条件查询
                    </span>
                    </div>
                    <el-form :model="formData" ref="formData" :inline="true" class="noMarginBottom">
                        <el-form-item label="账号:" prop="accountValue" class="mb1">
                            <el-input v-model.trim="formData.accountValue" placeholder="搜索账号..." size="small" class="inputWidth"></el-input>
                        </el-form-item>
                        <el-form-item label="用户名:" prop="userName" class="mb1">
                            <el-input v-model.trim="formData.userName" placeholder="搜索用户名..." size="small" class="inputWidth"></el-input>
                        </el-form-item>
                        <el-form-item label="状态:" prop="stateValue" class="mb1 ml20">
                            <el-select v-model="formData.stateValue" placeholder="请选择" size="small" class="inputWidth">
                                <el-option
                                        v-for="item in stateOptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item class="mb1 fltRt">
                            <el-button size="small" @click="resetForm('formData')" class="bkmgColor">重置</el-button>
                        </el-form-item>
                        <el-form-item class="mb1 fltRt">
                            <el-button type="primary" size="small" @click="query()" class="mr5">查询</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>

                <el-card>
                    <div slot="header">
                        <span>数据列表</span>
                    </div>
                    <el-button-group class="mb20">
                        <el-button size="small" @click="selectAll(getPageData())">全选</el-button>
                        <el-button @click="selectOther(getPageData())" size="small">反选</el-button>
                    </el-button-group>
                    <span class="fltRt">
                    <el-button type="primary" size="small" @click="addBatch">批量添加</el-button>
                </span>
                    <el-table
                            ref="multipleTable"
                            :data="getPageData()"
                            tooltip-effect="dark"
                            border
                            stripe
                            height="335"
                            :header-cell-style="getRowClass"
                            @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="55"></el-table-column>
                        <el-table-column prop="accountName" label="账号" width="200" show-overflow-tooltip></el-table-column>
                        <el-table-column prop="userName" label="用户名" width="200" show-overflow-tooltip></el-table-column>
                        <el-table-column prop="enable" label="状态" width="150" show-overflow-tooltip>
                            <template slot-scope="scope">
                                <span v-if="scope.row.enable=='1'">启用</span>
                                <span v-else>禁用</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="emailAddress" label="邮箱地址" show-overflow-tooltip></el-table-column>
                        <el-table-column label="操作" width="100" show-overflow-tooltip align="center">
                            <template slot-scope="scope">
                                <el-button
                                        title="添加"
                                        @click.native.prevent="add(scope.$index, scope.row)"
                                        type="text"
                                        icon="iconfont icon-tianjia"
                                        size="small">
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="textAlignRight mt30">
                        <el-pagination
                                layout="total,sizes,prev, pager, next,jumper"
                                @size-change="handleSizeChange"
                                :total="tableData.length"
                                :current-page.sync="currentPage"
                                :page-sizes="[5,10,15,20]"
                                :page-size="pagesize">
                        </el-pagination>
                    </div>
                </el-card>
            </div>
            <div class="bottomLayoutBus"></div>
        </el-container>
    </div>
    
</template>

<script>
    import urlConfig from '../../../config/url.json';
    import Vue from 'vue';
    import { Message } from 'element-ui';

    Vue.component(Message.name, Message);

    let role_ref_userNoListUrl = urlConfig.role_ref_userNoList;                      //角色-用户相关接口    查询角色-用户关联(未关联)
    let role_ref_userUrl=urlConfig.role_ref_user;                        //角色-用户相关接口      增加角色-用户关联
    export default {
        data(){
            return{
                currentPage:1,
                pagesize:5,
                formData:{
                    accountValue:'',
                    userName:'',
                    stateValue:'启用',
                },
                stateOptions: [{
                    value: '全部',
                },{
                    value: '启用',
                }, {
                    value: '禁用',
                }],
                tableData: [],
                multipleSelection: [],
                parameter:'',                               //页面传参
            }
        },
        methods:{
            //分页后的显示数据
            getPageData(){
                let that=this;
                return that.tableData.slice((that.currentPage-1)*that.pagesize,that.currentPage*that.pagesize);
            },
            
            getParams:function(){
                // 取到路由带过来的参数
                var routerParams = this.$route.query;
                // 将数据放在当前组件的数据内
                this.parameter = routerParams;
            },

            //获取所有数据
            getAllData(){
                let that=this;
                const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                });
                this.$http({
                    method: 'get',
                    url: role_ref_userNoListUrl,
                    baseURL:'/api',
                    params: {
                        roleId  : that.parameter.roleId,
                    }
                }).then(function(response){
                    debugger;
                    if(response.data.code==200) {
                        if(!response.data.data){
                            return;
                        }
                        that.tableData=response.data.data.msUsers;
                    }else{
                        Message.error('获取失败');
                    }
                    loading.close();
                }).catch(function(err){
                    console.log(err);
                    Message.error('获取失败');
                    loading.close();
                });
            },


            //返回
            back(){
                // this.$router.go(-1);
                this.$router.push({
                    path:'/mainPage/userRefRoleManage',
                    query: {
                        roleId: this.parameter.roleId,
                        roleName: this.parameter.roleName,
                    }
                })

            },

            //查询
            query(){
                let that=this;
                let paramsData='?roleId='+that.parameter.roleId;
                if(that.formData.accountValue){
                    paramsData=paramsData+'&accountName='+that.formData.accountValue;
                }
                if(this.formData.stateValue=='启用'){
                    paramsData=paramsData+'&enable=1'
                }else if(this.formData.stateValue=='禁用'){
                    paramsData=paramsData+'&enable=0'
                }else{
                    paramsData=paramsData;
                }
                if(that.formData.userName){
                    paramsData += '&userName=' + that.formData.userName;
                }
                const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                });
                this.$http({
                    method: 'get',
                    url: role_ref_userNoListUrl + paramsData,
                    baseURL:'/api'
                }).then(function(response){
                    if(response.data.code==200) {
                        if(!response.data.data){
                            return;
                        }
                        that.tableData=response.data.data.msUsers;
                    }else{
                        Message.error('查询失败');
                    }
                    loading.close();
                }).catch(function(err){
                    console.log(err);
                    Message.error('查询失败');
                    loading.close();
                });

            },


            //重置
            resetForm(formName) {
                this.$refs[formName].resetFields();
                let that=this;
                that.getAllData();
            },


            //批量添加
            addBatch(){
                let that=this;
                // let role_ref_userUrl=urlConfig.role_ref_user;                        //角色-用户相关接口      增加角色-用户关联
                let selectedTableValue=that.multipleSelection;
                if(selectedTableValue.length>0){
                    let userIdList=[];
                    let userNamesSuccess=[];
                    for(let i=0;i<selectedTableValue.length;i++){
                        userIdList.push(selectedTableValue[i].id);
                        userNamesSuccess.push(selectedTableValue[i].name);
                    }
                    const loading = this.$loading({
                        lock: true,
                        text: 'Loading',
                        spinner: 'el-icon-loading',
                    });
                    this.$http({
                        method: 'post',
                        url: role_ref_userUrl,
                        baseURL:'/api',
                        data:{
                            roleId:that.parameter.roleId,
                            userIdList :userIdList
                        }
                    }).then(function(response){
                        if(response.data.code==200) {
                            if(!response.data.data){
                                return;
                            }
                            Message.success('给   '  +'用户添加'+ that.parameter.roleName +'权限成功');
                            that.getAllData();
                        }else{
                            Message.error('给   '  +'用户添加'+ that.parameter.roleName +'权限失败');
                        }
                        loading.close();
                    }).catch(function(err){
                        Message.error('给   '  +'用户添加'+ that.parameter.roleName +'权限失败');
                        console.log(err);
                        loading.close();
                    });
                    userIdList=[];
                }else{
                    Message.warning('请选择用户');
                }
            },


            //添加
            add(index,row){
                let that=this;
                // let role_ref_userUrl=urlConfig.role_ref_user;                        //角色-用户相关接口      增加角色-用户关联
                let userIdList=[];
                userIdList.push(row.id);
                const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                });
                this.$http({
                    method: 'post',
                    url: role_ref_userUrl,
                    baseURL:'/api',
                    data:{
                        roleId:that.parameter.roleId,
                        userIdList :userIdList
                    }
                }).then(function(response){
                    if(response.data.code==200) {
                        if(!response.data.data){
                            return;
                        }
                        Message.success('给   '+ row.userName  +'用户添加'+ that.parameter.roleName +'权限成功');
                        that.getAllData();
                    }else{
                        Message.error('给   '+ row.userName  +'用户添加'+ that.parameter.roleName +'权限失败');
                    }
                    loading.close();
                }).catch(function(err){
                    Message.error('给   '+ row.userName  +'用户添加'+ that.parameter.roleName +'权限失败');
                    console.log(err);
                    loading.close();
                });

            },


            //全选
            selectAll(rows){
                rows.forEach(row=>{
                    //toggleAllSelection   用于多选表格，切换所有行的选中状态
                    this.$refs.multipleTable.toggleAllSelection(row);
                });
            },


            //反选
            selectOther(rows){
                rows.forEach(row=>{
                    //toggleRowSelection   用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
                    this.$refs.multipleTable.toggleRowSelection(row);
                });
            },


            //设置表头颜色
            getRowClass({ rowIndex }) {
                if (rowIndex == 0) {
                    return 'background:#F5F7FA'
                } else {
                    return ''
                }
            },


            //当选择项发生变化时会触发该事件
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },


            //1选择每页显示数据条数
            handleSizeChange(val) {
                this.pagesize=val;
            },
        },
        created:function(){
            this.getParams();
        },
        watch: {
            // 监测路由变化,只要变化了就调用获取路由参数方法将数据存储本组件即可
            '$route': 'getParams'
        },
        mounted(){

            let that=this;

            that.getAllData();
        }
    }
</script>

<style scoped>
    .inputWidth{
        width: 180px;
    }

    .headerCoster{
        height: 59px;
        border-top: 1px solid #eee;
        border-bottom: 1px solid #eee;
    }

    .buttonLineHeight{
        line-height: 60px;
    }

    .cardWidth{
        width: 100%;
    }
</style>